package com.ry.chat.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;


public class ChatServer {


    public static void main(String[] args) {
        ChatServer chatServer = new ChatServer();
        chatServer.server(8081);
    }

    public void server(int port) {
        EventLoopGroup parentExecutors = new NioEventLoopGroup(1);
        EventLoopGroup eventExecutors = new NioEventLoopGroup(10);
        ServerBootstrap serverBootstrap = new ServerBootstrap();

        try {
            serverBootstrap.group(parentExecutors, eventExecutors)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 1024)          // (5)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast("stringDecoder", new StringDecoder());
                            ch.pipeline().addLast("stringEncoder", new StringEncoder());

                            ch.pipeline().addLast(new ServerChannelInHandler());
                        }
                    });

//                    .childOption(ChannelOption.SO_KEEPALIVE, true); // (6)

            ChannelFuture f = serverBootstrap.bind(port).sync(); // (7)
            System.out.println("启动完成，等待连接");
            f.channel().closeFuture().sync();

        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            parentExecutors.shutdownGracefully();
            eventExecutors.shutdownGracefully();
        }

    }
}
